package com.tanhua.server.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.Query;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tanhua.common.mapper.SettingsMapper;
import com.tanhua.common.mapper.UserInfoMapper;
import com.tanhua.common.pojo.Announcement;
import com.tanhua.common.pojo.Settings;
import com.tanhua.common.pojo.User;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.dubbo.server.api.HuanXinApi;
import com.tanhua.dubbo.server.api.QuanZiApi;
import com.tanhua.dubbo.server.api.UsersApi;
import com.tanhua.dubbo.server.pojo.Comment;
import com.tanhua.dubbo.server.pojo.HuanXinUser;
import com.tanhua.dubbo.server.pojo.Users;
import com.tanhua.dubbo.server.vo.CommentType;
import com.tanhua.server.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class IMService {
    @Reference(version = "1.0.0")
    private UsersApi usersApi;
    @Reference(version = "1.0.0")
    private HuanXinApi huanXinApi;
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private SettingsMapper settingsMapper;

    @Autowired
    private UserInfoService userInfoService;

    @Reference(version = "1.0.0")
    private QuanZiApi quanZiApi;
    @Autowired
    private AnnouncementService announcementService;


    /**
     * 实现根据环信用户名查询个人的用户信息
     *
     * @param userName
     * @return
     */
    public UserInfoVo queryUserInfoByUserName(String userName) {
        //查询环信账户
        HuanXinUser huanXinUser = this.huanXinApi.queryUserByUserName(userName);
        if (ObjectUtil.isEmpty(huanXinUser)) {
            return null;
        }

        //查询用户信息
        UserInfo userInfo = this.userInfoService.queryUserInfoByUserId(huanXinUser.getUserId());
        if (ObjectUtil.isEmpty(userInfo)) {
            return null;
        }

        UserInfoVo userInfoVo = BeanUtil.copyProperties(userInfo, UserInfoVo.class, "marriage");
        userInfoVo.setGender(userInfo.getSex().toString().toLowerCase());
        userInfoVo.setMarriage(StrUtil.equals("已婚", userInfo.getMarriage()) ? 1 : 0);

        return userInfoVo;
    }


    /**
     * 添加好友
     *
     * @param friendId 好友id
     */
    public boolean contactUser(Long friendId) {
        User user = UserThreadLocal.get();
        String id = this.usersApi.saveUsers(user.getId(), friendId);
        if (StrUtil.isNotEmpty(id)) {
            //注册好友关系到环信
            return this.huanXinApi.addUserFriend(user.getId(), friendId);
        }
        return false;
    }

    /**
     * 获取自己的好友列表
     *
     * @param page
     * @param pageSize
     * @param keyword
     * @return好友列表
     */
    public PageResult getContacts(Integer page, Integer pageSize, String keyword) {
        try {
            PageResult pageResult = new PageResult();
            pageResult.setPage(page);
            pageResult.setPagesize(pageSize);
            User user = UserThreadLocal.get();
            Long userId = user.getId();
            List<Users> usersList;
            if (StrUtil.isEmpty(keyword)) {
                usersList = usersApi.getUsersList(userId, page, pageSize);
            } else {
                usersList = usersApi.getAllUsersList(userId);
            }
            QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
            wrapper.in("user_id", CollUtil.getFieldValues(usersList, "friendId"));
            if (StrUtil.isNotEmpty(keyword)) {
                wrapper.like("nick_name", keyword);
            }
            List<UserInfo> userInfos = userInfoMapper.selectList(wrapper);
            List<UsersVo> usersVos = new ArrayList<>();
            for (UserInfo userInfo : userInfos) {
                UsersVo usersVo = new UsersVo();
                usersVo.setId(userInfo.getUserId());
                usersVo.setAge(userInfo.getAge());
                usersVo.setAvatar(userInfo.getLogo());
                usersVo.setGender(userInfo.getSex().name().toLowerCase());
                usersVo.setNickname(userInfo.getNickName());
                //环信用户账号
                usersVo.setUserId("HX_" + String.valueOf(userInfo.getUserId()));
                usersVo.setCity(StringUtils.substringBefore(userInfo.getCity(), "-"));
                usersVos.add(usersVo);
            }
            pageResult.setItems(usersVos);
            return pageResult;
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 查询点赞,喜欢和评论列表
     *
     * @param page
     * @param pageSize
     * @param like
     * @return
     */
    public PageResult queryCommentList(Integer page, Integer pageSize, CommentType like) {
        User user = UserThreadLocal.get();
        Long userId = user.getId();
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);
        List<Comment> comments = quanZiApi.messagesAllComment(page, pageSize, like, userId);
        if (CollUtil.isEmpty(comments)) {
            return pageResult;
        }
        //封装信息
        List<MessageCommentVo> messageCommentVos = new ArrayList<>();
        for (Comment comment : comments) {
            MessageCommentVo messageCommentVo = new MessageCommentVo();
            QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
            wrapper.eq("user_id", comment.getUserId());
            UserInfo userInfo = userInfoMapper.selectOne(wrapper);
            messageCommentVo.setAvatar(userInfo.getLogo());
            messageCommentVo.setCreateDate(DateUtil.format(new Date(comment.getCreated()), "yyyy-MM-dd HH:mm"));
            messageCommentVo.setNickname(userInfo.getNickName());
            messageCommentVo.setId(comment.getId().toHexString());
            messageCommentVos.add(messageCommentVo);
        }
        pageResult.setItems(messageCommentVos);
        return pageResult;
    }

    /**
     * 查询公告列表
     *
     * @param page
     * @param pageSize
     * @return
     */
    public PageResult queryMessageAnnouncementList(Integer page, Integer pageSize) {
        PageResult pageResult = new PageResult();
        pageResult.setPagesize(pageSize);
        pageResult.setPage(page);
        IPage<Announcement> announcements = announcementService.getAnnouncements(page, pageSize);
        //封装公告信息
        List<AnnouncementVo> lists = new ArrayList<>();
        for (Announcement announcement : announcements.getRecords()) {
            AnnouncementVo announcementVo = new AnnouncementVo();
            announcementVo.setDescription(announcement.getDescription());
            announcementVo.setTitle(announcement.getTitle());
            announcementVo.setId(StrUtil.toString(announcement.getId()));
            announcementVo.setCreateDate(DateUtil.format(announcement.getCreated(), "yyyy-MM-dd HH:mm"));
            lists.add(announcementVo);
        }
        pageResult.setItems(lists);
        return pageResult;
    }

    /**
     * 删除好友关系
     *
     * @param likeUserId
     */
    public void deleteContactUser(Long likeUserId) {
        User user = UserThreadLocal.get();
        Long userId = user.getId();
        Boolean aBoolean = this.usersApi.removeUsers(userId, likeUserId);
        if (aBoolean) {
            Boolean aBoolean1 = this.huanXinApi.removeUserFriend(userId, likeUserId);
            if (aBoolean1) {
                return;
            }
        }
        return;
    }


    /**
     * 获取通用设置
     *
     * @param userId
     * @return
     */
    public Settings findSettings(Long userId) {
        QueryWrapper<Settings> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",userId);
        Settings settings = settingsMapper.selectOne(wrapper);
        return settings;
    }
}
